package com.nameless.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nameless.config.AlipayConfig;
import com.nameless.entity.Order;
import com.nameless.feign.OrderFeign;
import com.nameless.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author keluoyisi
 */
@SuppressWarnings("all")
@Component
public class AlipayUtil {

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private OrderFeign orderFeign;

    /**
     * 支付方法返回一个二维码地址
     * @param
     * @return
     * @throws AlipayApiException
     */
    public String pay(Order order) throws AlipayApiException {
        // 1、获得初始化的AlipayClient
        String serverUrl = alipayConfig.getGatewayUrl();
        String appId = alipayConfig.getAppId();
        String privateKey = alipayConfig.getPrivateKey();
        String format = "json";
        String charset = alipayConfig.getCharset();
        String alipayPublicKey = alipayConfig.getPublicKey();
        String signType = alipayConfig.getSignType();
        String returnUrl = alipayConfig.getReturnUrl();
        String notifyUrl = alipayConfig.getNotifyUrl();
        AlipayClient alipayClient = new DefaultAlipayClient(
                serverUrl, appId,
                privateKey, format, charset, alipayPublicKey, signType);

        //二维码
        AlipayTradePrecreateRequest request=new AlipayTradePrecreateRequest();
        // 支付请求
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" +order.getOrderNo() + "\"," +//商户订单号
                "    \"total_amount\":\"" + order.getTotalPrice() + "\"," +
                "    \"subject\":\"" + "app" + "当面付" + "\"," +
                "    \"store_id\":\"00100\"," + // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
                "    \"timeout_express\":\"30m\"}");//订单允许的最晚付款时间
        AlipayTradePrecreateResponse response = null;
        //支付宝二维码URL
        String qrCode = "";
        try {
            response = alipayClient.execute(request);
            if (!response.isSuccess()) {
                throw new AlipayApiException("支付失败");
            }
            qrCode = response.getQrCode();

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return qrCode;
    }

    /**
     * 返回验证
     */

    public Result getReturn(Order order) throws AlipayApiException {

        // 1、获得初始化的AlipayClient
        String serverUrl = alipayConfig.getGatewayUrl();
        String appId = alipayConfig.getAppId();
        String privateKey = alipayConfig.getPrivateKey();
        String format = "json";
        String charset = alipayConfig.getCharset();
        String alipayPublicKey = alipayConfig.getPublicKey();
        String signType = alipayConfig.getSignType();
        String returnUrl = alipayConfig.getReturnUrl();
        String notifyUrl = alipayConfig.getNotifyUrl();
        AlipayClient alipayClient = new DefaultAlipayClient(
                serverUrl, appId,
                privateKey, format, charset, alipayPublicKey, signType);


        //验证处理
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\""+order.getOrderNo()+"\"}"); //设置业务参数
        AlipayTradeQueryResponse response =
                alipayClient.execute(request);//通过alipayClient调用API，获得对应的response类

        System.out.print(response.getBody());
        String money = response.getBuyerPayAmount();
        if (!"0.00".equals(money)){
            Result result = orderFeign.updateOrder(order.getOrderNo(),order.getTotalPrice());
            return  result;
        }else {
            return  new Result(2001,"失败支付");
        }
    }

    /**
     * 返回验证
     */

    public Result getReturn(String orderNo) throws AlipayApiException {

        // 1、获得初始化的AlipayClient
        String serverUrl = alipayConfig.getGatewayUrl();
        String appId = alipayConfig.getAppId();
        String privateKey = alipayConfig.getPrivateKey();
        String format = "json";
        String charset = alipayConfig.getCharset();
        String alipayPublicKey = alipayConfig.getPublicKey();
        String signType = alipayConfig.getSignType();
        String returnUrl = alipayConfig.getReturnUrl();
        String notifyUrl = alipayConfig.getNotifyUrl();
        AlipayClient alipayClient = new DefaultAlipayClient(
                serverUrl, appId,
                privateKey, format, charset, alipayPublicKey, signType);


        //验证处理
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\""+orderNo+"\"}"); //设置业务参数
        AlipayTradeQueryResponse response =
                alipayClient.execute(request);//通过alipayClient调用API，获得对应的response类

        System.out.print(response.getBody());
        String money = response.getBuyerPayAmount();
        if (!"0.00".equals(money)){
//            Result result = orderFeign.updateOrder(orderNo);
            return new Result<>(200,"支付成功",null);
        }else {
            return  new Result(2001,"失败支付");
        }
    }

    /**
     * 支付方法返回一个二维码地址
     * @param
     * @return
     * @throws AlipayApiException
     */
    public Map<String, Object> pay(String orderNo, BigDecimal totalPrice) throws AlipayApiException {

        // 1、获得初始化的AlipayClient
        String serverUrl = alipayConfig.getGatewayUrl();
        String appId = alipayConfig.getAppId();
        String privateKey = alipayConfig.getPrivateKey();
        String format = "json";
        String charset = alipayConfig.getCharset();
        String alipayPublicKey = alipayConfig.getPublicKey();
        String signType = alipayConfig.getSignType();
        String returnUrl = alipayConfig.getReturnUrl();
        String notifyUrl = alipayConfig.getNotifyUrl();
        AlipayClient alipayClient = new DefaultAlipayClient(
                serverUrl, appId,
                privateKey, format, charset, alipayPublicKey, signType);

        //二维码
        AlipayTradePrecreateRequest request=new AlipayTradePrecreateRequest();
        // 支付请求
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" +orderNo + "\"," +//商户订单号
                "    \"total_amount\":\"" + totalPrice + "\"," +
                "    \"subject\":\"" + "app" + "当面付" + "\"," +
                "    \"store_id\":\"00100\"," + // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
                "    \"timeout_express\":\"30m\"}");//订单允许的最晚付款时间
        AlipayTradePrecreateResponse response = null;
        //支付宝二维码URL
        String qrCode = "";
        Map<String,Object> result=new HashMap<>();
        try {
            response = alipayClient.execute(request);
            if (!response.isSuccess()) {
                throw new AlipayApiException("支付失败");
            }

            result.put("codeUrl",response.getQrCode());
            result.put("price",totalPrice);
            result.put("orderNo",orderNo);
//            qrCode = response.getQrCode();

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return result;
    }
}
